<template>
  <div class="component page">
    <div class="container-center">
      <div class="over-hidden">
        <router-link
          class="btn btn-default pull-right icon icon-arrowsleftline mt-lg"
          :to="getMicroRoute('/tools')"
        >
          返回列表</router-link>
        <h2 class="text-left">二维码</h2>
      </div>
      <div class="over-hidden">
        <div class="btns-row" style="padding: 12px 0">
          <a @click="handleCreate" class="btn btn-default mr-md">生成</a>
          <a @click="handleDownload" class="btn btn-default mr-md">下载二维码</a>
          <a @click="handleImportData" class="btn btn-default mr-md">导入二维码图片</a>
        </div>
      </div>
      <div class="over-hidden">
        <div class="form-group">
          <label class="form-label">
            二维码:
          </label>
          <div id="qr_code" class="over-hidden">
            <span class="text-lightgray">未生成</span>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="qrcode-view">
          <div class="form-group">
            <label class="form-label">
              字符串:
            </label>
            <input
              type="text" class="form-input" placeholder="请输入转化字符"
              v-model="value"
            />
          </div>
          <div class="form-group hidden">
            <label class="form-label">图片转Base64：</label>
            <div class="form-field">
              <input
                @change="handleChangeFile" class="form-input" type="file"
                accept="image/png,image/jpeg,image/jpg,image/gif,image/bmp" />
            </div>
          </div>
        </div>
        <label class="form-label">
          长/宽:
        </label>
        <input
          type="text" class="form-input"
          v-model="width"
        />
      </div>
      <div class="form-group">
        <label class="form-label">
          亮色:
        </label>
        <input
          type="color" class="form-input"
          v-model="colorDark"
        />
        <label class="form-label">
          浅色:
        </label>
        <input
          type="color" class="form-input"
          v-model="colorLight"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { filer } from '@daelui/dogjs/dist/components'
import '@vendor/qrcode/1.1.0/js/qrcode.js'
import '@vendor/reqrcode/1.1.0/reqrcode.js'

/* JSON转换 */
export default {
  data () {
    return {
      value: '', // 字符串
      width: 256,
      colorDark: '#000000',
      colorLight: '#ffffff'
    }
  },

  methods: {
    /**
     * @description 初始化
     */
    init () {
  
    },
    /**
     * @description 生成
     */
    handleCreate(){
      this.toQRCode(this.value)
    },
    // 下载
    handleDownload () {
      this.downLoad()
    },
    /**
     * @description 导入数据
     */
    handleImportData () {
      document.querySelector('input[type=file]').click()
    },
    getWidth () {
      let width = parseFloat(this.width)
      width = isNaN(width) ? 256 : width
      width = width < 64 ? 64 : width
      return width
    },
    // 生成二维码
    toQRCode (text) {
      let el = document.getElementById('qr_code')
      let width = this.getWidth()
      el.innerHTML = ''
      var qrcode = new QRCode(el, {
        width: width,
        height: width,
        colorDark: this.colorDark || '#000000',
        colorLight: this.colorLight || '#ffffff',
        correctLevel: 3
      })
      qrcode.makeCode(text)
    },
    downLoad () {
      let el = document.getElementById('qr_code')
      let img = el.querySelector('img')
      if (img) {
        this.downloadImage(img.src, 'qrcode-image.png')
      } else {
        alert('图片未生成')
      }
    },
    downloadImage (url, downloadName) {
      const link = document.createElement('a')
      link.setAttribute('download', downloadName)
      const image = new Image()
      // 添加时间戳，防止浏览器缓存图片
      image.src = url
      // 设置 crossOrigin 属性，解决图片跨域报错
      image.setAttribute('crossOrigin', 'Anonymous')
      image.onload = () => {
        link.href = this.getImageBase64(image)
        link.click()
      }
    },
    getImageBase64(image) {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      // 获取图片后缀名
      const extension = image.src
        .substring(image.src.lastIndexOf('.') + 1)
        .toLowerCase()
      // 某些图片 url 可能没有后缀名，默认是 png
      return canvas.toDataURL('image/' + extension, 1)
    },
    // 文件转化为base64
    getObjectURL (file) {
      var url = null
      if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
      }
      return url
    },

    // 上传二维码
    handleChangeFile (e) {
      let file = e.target.files[0]
      if (filer) {
        filer.fileToBase64(file).then(result => {
          let img = document.createElement('img')
          img.src = result
          let width = this.getWidth()
          img.width = width
          img.height = width
          let el = document.getElementById('qr_code')
          el.innerHTML = ''
          el.appendChild(img)
          this.resolveQRCode(img)
        })
      }
    },
    // 解析二维码
    resolveQRCode (img) {
      img = img || {}
      qrcode.decode(img.src)
      qrcode.callback = (res) => {
        if (res === 'error decoding QR Code') {
          alert('该图片不是二维码')
        } else {
          this.value = res
        }
      }
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang="less">

</style>
